package com.example.demo.controller;

import com.example.demo.Excel.ExcelExportService;
import com.example.demo.mapper.CompetitionScoreMapper;
import com.example.demo.pojo.Competitions.CompetitionScoreDTO;
import com.example.demo.pojo.Competitions.Competitions;
import com.example.demo.pojo.Competitions.ManageInvitedUsersRequest;
import com.example.demo.pojo.Competitions.VipCompetitionDetail;
import com.example.demo.pojo.R;
import com.example.demo.pojo.User.InvitedUserDTO;
import com.example.demo.service.CompetitionScoreService;
import com.example.demo.service.CompetitionService;
import com.example.demo.service.UserService;
import com.example.demo.service.VipCompetitionService;
import com.example.demo.utils.TokenUtil.JwtUtils;
import com.example.demo.utils.UserUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/vips/Competitions")
public class VipCompetitionController {

    private static final Logger logger = LoggerFactory.getLogger(VipCompetitionController.class);

    @Autowired
    private VipCompetitionService vipCompetitionService;
    @Resource
    private CompetitionScoreService competitionScoreService;

    @Autowired
    private ExcelExportService excelExportService;

    @Resource
    private CompetitionScoreMapper competitionScoreMapper;
    @Resource
    private CompetitionService competitionService;

    @Autowired
    private UserService userService;

    @Resource
    private UserUtil userUtil;

    /**
     * 创建比赛接口。
     *
     * @param competitions 比赛信息
     * @param token        用户登录时获取的Token
     * @return 创建结果
     */
    @PostMapping("/createCompetition")
    public R<Map<String, String>> createCompetition(@RequestBody Competitions competitions,
                                                    @CookieValue(name = "token", required = false) String token) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("用户未登录或Token无效");
            return R.failed("用户未登录或登录异常");
        }

        try {
            return vipCompetitionService.creatCompetition(competitions, token);
        } catch (Exception e) {
            logger.error("创建比赛失败", e);
            return R.failed("创建比赛失败");
        }
    }

    /**
     * 管理比赛的邀请用户列表。
     *
     * @param token 用户登录时获取的Token
     * @return 操作结果
     */
    @PostMapping("/manageInvitedUsers")
    public R<T> manageInvitedUsers(@CookieValue(name = "token", required = false) String token,
                                   @RequestBody ManageInvitedUsersRequest manageInvitedUsersRequest) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("用户未登录或Token无效");
            return R.failed("用户未登录或登录异常");
        }

        try {
            return vipCompetitionService.manageInvitedUsers(token,
                    manageInvitedUsersRequest.getCompetitionId()
                    , manageInvitedUsersRequest.getUserIds()
                    , manageInvitedUsersRequest.getIsInviting());
        } catch (Exception e) {
            logger.error("管理邀请用户列表失败", e);
            return R.failed("管理邀请用户列表失败");
        }
    }

    /**
     * 获取比赛排名接口
     *
     * @param token token
     * @param id    比赛id
     */
    @PostMapping("/getCompetitionScoreById")
    public R<List<CompetitionScoreDTO>> getCompetitionScoreById(@CookieValue(name = "token", required = false) String token
            , @RequestParam Integer id) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("用户未登录或Token无效");
            return R.failed("用户登录异常或未登录！");
        }
        try {
            return competitionScoreService.getCompetitionScoreById(token, id);
        } catch (Exception e) {
            logger.error("获取比赛排名失败", e);
            return R.failed("获取比赛排名失败");
        }
    }

    /**
     * 比赛排名信息Excel导出
     *
     * @param id 比赛id
     */
    @GetMapping("/exportCompetitionScore")
    public void exportCompetitionScore(HttpServletResponse response,
                                       @CookieValue(name = "token", required = false) String token,
                                       Integer id) throws IOException {
        File tempFile = null;
        try {
            // 获取并验证Token
            if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
                throw new Exception("用户未登录或登录异常");
            }


            // 根据id查询
            List<CompetitionScoreDTO> competitionScoreDTOS = competitionScoreMapper.selectCompetitionScoresList(id);


            // 创建临时文件
            tempFile = File.createTempFile("competitionScore_", ".xlsx");

            // 导出数据到临时文件
            excelExportService.exportCompetitionScore(competitionScoreDTOS, tempFile.getAbsolutePath());

            // 设置响应头
            String fileName = "比赛排名信息.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String file = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + file);

            // 从临时文件读取数据并写入响应
            Files.copy(tempFile.toPath(), response.getOutputStream());
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }
    /**
     * 获取参赛用户接口
     *
     * @param token token
     * @param id    比赛id
     * @return 参赛用户
     */
    @GetMapping("/getJoinCompetitionUserById")
    public R<Map<String, Object>> getJoinCompetitionUserById(@CookieValue(name = "token", required = false) String token
            , @RequestParam int id
            , @RequestParam int pageNum
            , @RequestParam int pageSize) {
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("Token为空");
            return R.failed("未登录或登录异常");
        }

        try {
            return competitionService.getJoinCompetitionUserById(id, pageNum, pageSize);
        } catch (Exception e) {
            logger.error("错误！", e);
            return R.failed("获取参赛用户失败");
        }
    }

    /**
     * vip用户获取被邀请用户id接口
     * @param realName 用户真实姓名
     * @return 用户id
     */
    @GetMapping("/getUserIdByName")
    public R<List<InvitedUserDTO>> getUserIdByName(@RequestParam String realName){
        try {
            return userService.getUserIdByName(realName);
        } catch (Exception e) {
            logger.error("错误！", e);
            return R.failed("查询失败！");
        }
    }

    /**
     * 获取vip用户创建所有比赛
     * @param token token
     * @return 比赛集合（包含口令）
     */
    @GetMapping("/getCreatCompetitions")
    public R<List<VipCompetitionDetail>> getCreatCompetitions(@CookieValue(name = "token", required = false) String token){
        if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
            logger.warn("Token为空");
            return R.failed("未登录或登录异常");
        }

        try {
            return vipCompetitionService.getCreatCompetitions(token);
        } catch (Exception e) {
            logger.error("错误！", e);
            return R.failed("获取失败");
        }
    }
}
